package com.szyportal.common.utils.ssh;


import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.auth.StaticUserAuthenticator;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;

public class ScpWithVFS {
    String host = "远程服务器IP";
    String port = "端口号";
    String username = "用户名";
    String password = "密码";
    String localDir = "本地目录路径";
    String remoteDir = "远程目录路径";

    /**
     *
     * @param host
     * @param port
     * @param username
     * @param password
     * @param localDir
     * @param remoteDir
     */
    public ScpWithVFS(String host,String port,String username,String password,String localDir,String remoteDir){
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.localDir = localDir;
        this.remoteDir = remoteDir;
    }

    public boolean start() {
        try {
            StaticUserAuthenticator auth = new StaticUserAuthenticator(null, username, password);
            FileSystemOptions opts = new FileSystemOptions();
            DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

            // 构建远程路径URI
            String remoteUri = "sftp://" + host + "/" + remoteDir;

            FileSystemManager fsManager = VFS.getManager();

            // 获取本地和远程文件对象
            FileObject localFile = fsManager.resolveFile(localDir);
            FileObject remoteFile = fsManager.resolveFile(remoteUri, opts);

            // 拷贝目录
            remoteFile.copyFrom(localFile, Selectors.SELECT_ALL);

            System.out.println("目录拷贝完成!");
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }


    }
}